import java.util.Map;
import java.util.TreeMap;

class Solution1705 {
    private boolean process(TreeMap<Integer, Integer> appleMap, int day){
        Map.Entry<Integer, Integer> et = appleMap.ceilingEntry(day);
        if(et != null){
            if(et.getValue() > 1)
                appleMap.put(et.getKey(), et.getValue() - 1);
            else{
                appleMap.remove(et.getKey());
            }
            return true;
        }
        return false;
    }


    public int eatenApples(int[] apples, int[] days) {
        int n = apples.length;
        TreeMap<Integer, Integer> appleMap = new TreeMap<>();
        int res = 0;
        for (int i = 0; i < n; i++) {
            int appleCount = apples[i];
            int dayCount = days[i];
            if(appleCount != 0 && dayCount != 0) {
                int lastCanEatDay = i + dayCount - 1;
                appleMap.put(lastCanEatDay, appleMap.getOrDefault(lastCanEatDay, 0) + appleCount);
            }
            if(process(appleMap, i)){
                res++;
            }
        }
        if(appleMap.isEmpty()){
            return res;
        }
        Integer maxDay = appleMap.lastKey();
        for (int i = n; i <= maxDay; i++) {
            if(process(appleMap, i)) {
                res++;
            }
        }
        return res;
    }
}